import React from 'react';
import { Layout } from 'antd';
import { isRouteErrorResponse, json, useLoaderData, useRouteError, LoaderFunctionArgs } from 'react-router-dom';

const { Content } = Layout;
export function projectLoader({ params }: LoaderFunctionArgs) {
    if (params.projectId === 'unauthorized') {
        // 抛出未授权错误
        throw json({ contactEmail: 'administrator@fake.com' }, { status: 401 });
    }

    if (params.projectId === 'broken') {
        // Uh oh - in this flow we somehow didn't get our data nested under `project`
        // and instead got it at the root - this will cause a render error!
        return json({
            id: params.projectId,
            name: 'Break Some Stuff',
            owner: 'The Joker',
            deadline: 'June 2022',
            cost: 'FREE',
        });
    }

    return json({
        project: {
            id: params.projectId,
            name: 'Build Some Stuff',
            owner: 'Joe',
            deadline: 'June 2022',
            cost: '$5,000 USD',
        },
    });
}

export function Project() {
    const { project } = useLoaderData() as any;

    return (
        <Layout className=''>
            <Content className='flex flex-col items-center  mt-10'>
                <h1>
                    Project Name:
                    {project.name}
                </h1>
                <p>
                    Owner:
                    {project.owner}
                </p>
                <p>
                    Deadline:
                    {project.deadline}
                </p>
                <p>
                    Cost:
                    {project.cost}
                </p>
            </Content>
        </Layout>
    );
}

// 401 未授权 其他报错抛出
export function ProjectErrorBoundary() {
    const error = useRouteError();

    // We only care to handle 401's at this level, so if this is not a 401
    // ErrorResponse, re-throw to let the RootErrorBoundary handle it
    if (!isRouteErrorResponse(error) || error.status !== 401) {
        throw error;
    }

    return (
        <Layout className=''>
            <Content className='flex flex-col items-center  mt-10'>
                <h1>您没有访问此项目的权限</h1>
                <p>
                    请联系
                    <a href={`mailto:${error?.data?.contactEmail}`}>{error?.data?.contactEmail}</a>
                    获得访问权限。
                </p>
            </Content>
        </Layout>
    );
}
